'use strict';
/* 全局变量(数据) */

const Controller = require('egg').Controller;
const fruitList = [
  '🍌 banana',
  '🍎 ',
  '🍐 ',
];
/* 定义对应的controller. */
class FruitsController extends Controller {
  async index() {
    // get paramter by query.
    const query = this.ctx.request.query;
    console.log(query);
    this.ctx.body = 'this is a fruits list.';
    this.ctx.body += fruitList;
    // this.ctx.body=`the passed value by url is ${query.index}`

  }
  async new() {
    /* 在此处(前端页面提交数据的入口.post到/fruits(url)页面) */
    this.ctx.body = `
        <form method = 'post' action='/fruits'>
            <input name='fruitName'>
            <button>add</button>
        </form >
        `;
  }
  /* restful的接口之一,对应post */
  async create() {
    /* 添加水果到水果列表(添加的内容通过前端输入,经由post请求传递到服务器,也就是在本函数会被处理) */
    const fruit = this.ctx.request.body;
    // this.ctx.body = fruit;
    // add a new item to the fruitList array(list)
    /* 将请求中的参数提取出来,插入到后端中的数据容器(可以时数据库之类的.) */
    fruitList.push(fruit.fruitName);
    // this.ctx.body = 'add successfully'
    /* 插入完成之后重定向网页到水果页面,将变更后的容器中的数据渲染出来 */
    this.ctx.redirect('/fruits');
  }

  /*   async destroy() {

    }
    async update() {
 
    } */


  async getId() {
    let id = this.ctx.params.id;
    // params mode to request valuses.
    this.ctx.body = `the passed id is : ${id}`;
  }
  async createPage() {
    this.ctx.body = `
          <form method = 'post' action='/createFruit'>
              <input name='fruitName'>
              <button>add</button>
          </form >
          `;
  }
  async createFruit() {
    let fruit = this.ctx.request.body;
    this.ctx.body = fruit;
    this.ctx.body = 'add successfully';
  }
}

module.exports = FruitsController;
